package com.see.server.command;

import java.util.HashMap;

import com.see.domain.Protocol;
import com.see.exception.MessegeFeedException;
import com.see.exception.NoSuchSocketConnectionException;
import com.see.exception.UserNotAuthenticatException;
import com.see.server.ServerCore;
import com.see.server.SocketConnection;

public class CloseCommand implements Command {

	private String username;
	private SocketConnection socketConnection;
	
	public CloseCommand(SocketConnection socketConnection ,HashMap<String, String> paramMap){
		username = paramMap.get("USERNAME");
		this.socketConnection = socketConnection;
	}

	@Override
	public String execute() throws UserNotAuthenticatException, MessegeFeedException {
		
		if (username == null) {
			throw new MessegeFeedException(Protocol.errormsg(Protocol.CLOSE_FIELD, Protocol.ERROR_USERNAME));
		}
		
		if(!socketConnection.isAuthenticated())
			throw new UserNotAuthenticatException(Protocol.errormsg(Protocol.CLOSE_FIELD, Protocol.ERROR_USERNOTAUTH));
	
		
		try {
			ServerCore.getInstance().removeConnection(username);
		} catch (NoSuchSocketConnectionException e) {
			throw new UserNotAuthenticatException(Protocol.errormsg(Protocol.CLOSE_FIELD, Protocol.ERROR_USERNOTAUTH));
		}
	
		return Protocol.successmsg(Protocol.CLOSE_FIELD, "");
	}

}
